package com.cisdi.blog.service.impl;

import com.cisdi.blog.dao.TagRepository;
import com.cisdi.blog.entity.Tag;
import com.cisdi.blog.exception.NotFoundException;
import com.cisdi.blog.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author pengyangyan
 * @version 1.0.0
 * @date 2020年03月19日 16:38:00
 */
@Service
public class TagServiceImpl implements TagService {

    @Autowired
    TagRepository tagRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Tag saveTag(Tag tag) {
        return tagRepository.save(tag);
    }

    @Override
    public Tag getTag(Long id) {
        Optional<Tag> tag = tagRepository.findById(id);
        if (!tag.isPresent()){
            throw new NotFoundException("不存在该标签或标签已被删除");
        }
        return tag.get();
    }

    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }

    @Override
    public List<Tag> hotTag(Integer size) {
        Pageable pageable = PageRequest.of(0, size);
        return tagRepository.getTop(pageable);
    }

    @Override
    public List<Tag> listTag() {
        return tagRepository.findAll();
    }

    @Override
    public List<Tag> listTag(String ids) {
        List<Long> longs = converToList(ids);
        List<Tag> all = tagRepository.findAllById(longs);
        System.out.println(all.size());
        return all;
    }

    private List<Long> converToList(String ids){
        List<Long> idList = new ArrayList<>();
        if (!StringUtils.isEmpty(ids)){
            String[] strings = ids.split(",");
            if (strings.length>0){
                for (String id : strings) {
                    idList.add(Long.valueOf(id));
                }
            }
        }
        return idList;
    }

    @Override
    public Tag updateTag(Long id, Tag tag) {
        Optional<Tag> optional = tagRepository.findById(id);
        if (!optional.isPresent()){
            throw new NotFoundException("不存在该标签或标签已被删除");
        }
        Tag tag1 = optional.get();
        BeanUtils.copyProperties(tag,tag1);
        return tagRepository.save(tag1);
    }

    @Override
    public void removeTag(Long id) {
        tagRepository.deleteById(id);
    }

    @Override
    public Tag findTagByName(String name) {
        return tagRepository.findTagByName(name);
    }
}
